package com.abss.vote.util;

import com.abss.vote.model.MpInfo;
import com.abss.vote.service.UserReceptionService;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.List;

public class WxShare {

    @Autowired
    private UserReceptionService userReceptionService;

    /**
     * 第一步，获取access_token
     * @param appId
     * @param appSecret
     * @return
     */
    public static String getAccess_token(String appId, String appSecret){

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
        //System.out.println("分享获取："+url);
        String accessToken = null;
        try
        {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            JSONObject jsonObj = JSONObject.fromObject(message);
            accessToken = jsonObj.getString("access_token");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return accessToken;
    }


    /**
     * 第二步：获得ACCESS_TICKET
     * @param access_token
     * @return
     */
    public static String getAccess_ticket(String access_token) {
        System.out.println("access_token::::"+access_token);
        String ticket = null;
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token +"&type=jsapi";//这个url链接和参数不能变
        try {
            URL urlGet = new URL(url);
            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
            http.setRequestMethod("GET"); // 必须是get方式请求
            http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            http.setDoOutput(true);
            http.setDoInput(true);
            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
            http.connect();
            InputStream is = http.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes, "UTF-8");
            System.out.println("message::::"+message);
            JSONObject demoJson = JSONObject.fromObject(message);
            ticket = demoJson.getString("ticket");
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticket;
    }


    /**
     * 第三步：SHA1加密
     * @param decript
     * @return
     */
    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     *  检测评论内容安全
     * @param textConetnt
     * @return
     */
    public static boolean checkText(String textConetnt,String accessToken) {
        System.out.println("内容："+textConetnt+"<>accessToken:"+accessToken);

        String getMPCode= "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=" + accessToken;
        try {
            URL url = new URL(getMPCode);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setRequestProperty("Content-type", "application/json;charset=UTF-8");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            OutputStream out=conn.getOutputStream();

            out.write(("{\"content\":\""+textConetnt+"\"}").getBytes("UTF-8"));
            out.flush();
            out.close();
            conn.connect();


            if (conn.getResponseCode() != 200)return false;

            InputStream stream=conn.getInputStream();

            byte[] buf = new byte[1024*1024];

            int len=-1;
            int readcount=0;
            while((len= stream.read(buf, readcount, buf.length-readcount))!=-1){
                readcount+=len;
            }

            byte[] result=new byte[readcount];
            System.arraycopy(buf,0,result,0,readcount);

            String ret=new String(result,"utf-8");

            System.out.println("微信返回："+ret);
            JSONObject demoJson = JSONObject.fromObject(ret);

            int code=demoJson.getInt("errcode");

            return code==0;
        }
        catch (Exception e) {
            e.printStackTrace();
            return false;
        }


    }




}
